﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Sl.Log;
using ChholCmdPort;
using ChholConfig.Configer;

namespace ChholConfig {

	public partial class LuaForm : PortUserForm {
		public LuaForm() {
			InitializeComponent();
		}
		LoggerToRTB rtblog;
		LuaCmd lua;
		static public (string word, Color color)[] sr_color_pair = {
			("警告", Color.DarkRed),
			("脚本", Color.DarkGreen),
			("执行",Color.DarkOrchid),
			("消息",Color.SeaGreen),
			("错误", Color.DarkOrange),
		};
		public LuaForm(RecvFanOut fan_out, Form main_form)
			: base(global::ChholConfig.Properties.Resources.Lua_Language_50px, 48, fan_out, "Lua执行器") {
			InitializeComponent();
			openScriptFile.InitialDirectory = System.Environment.CurrentDirectory+"\\Lua\\";
			rtblog = new LoggerToRTB(rsRTB) { word_color_pair = sr_color_pair };
		}
		protected override void turnOn() {
			lua = new LuaCmd(Port_user, rtblog);
			cmdCRTB.inputCmd = inputCmd;
			lua.startLua(); rtblog.LogLine($"【执行】启动lua执行器");
			//启用整个界面
			cmdCRTB.Enabled = commonTS.Enabled = true;
		}

		private bool inputCmd(string cmd) {
			rtblog.LogLine($"【执行】{cmd}");
			lua.doLua(cmd);
			return true;
		}
		protected override void OnClosing(CancelEventArgs e) {
			base.OnClosing(e);
			lua?.Dispose();
		}


		private void resetLua_Click(object sender, EventArgs e) {
			lua.restartLua(); rtblog.LogLine($"【执行】重启lua执行器");
		}
		string current_file = "";

		private void openScriptFile_FileOk(object sender, CancelEventArgs e) {
			FilePathTB.Text = openScriptFile.FileName;
			current_file = $"dofile('{FilePathTB.Text.Replace("\\", "/")}')";
			reloadFile_Click(sender, e);
		}

		private void FilePathTB_Click(object sender, EventArgs e) {
			openScriptFile.ShowDialog();
		}

		private void reloadFile_Click(object sender, EventArgs e) {
			lua.restartLua(); rtblog.LogLine($"【执行】重启lua执行器");
			lua.doLua(current_file);
			rtblog.LogLine($"【执行】{current_file}");

		}

		private void ClearBTN_Click(object sender, EventArgs e) {
			if (rsRTB.Text.Length > 3200) {
				var index = rsRTB.Text.IndexOf('\n', rsRTB.TextLength - 3000);
				//rsRTB删除index前面的内容
				rsRTB.ReadOnly = false;
				rsRTB.Select(0, index);
				rsRTB.SelectedText = "";
				rsRTB.ReadOnly = true;
				rsRTB.Select(rsRTB.TextLength, 0);
				rsRTB.ScrollToCaret();
			} else {
				rsRTB.Clear();
			}
		}
	}
}
